/***********************************************
* Filename:  		DXHandler.cpp
* Date:      		01/12/2014
* Mod. Date: 		01/12/2014
* Author:    		Night
* Purpose:   		Handles the DirectX 9 Graphics API
************************************************/

#include "DXHandler.h"
#include "../../UniInclude.h"
#include "DXScreenRender.h"

CDXHandler::CDXHandler(void)
{
	m_pD3DObject = nullptr;
	m_pD3DDevice = nullptr;
	ZeroMemory( &m_D3DPresentParam, sizeof( m_D3DPresentParam ) );
	m_pScreenRender= nullptr;
};

CDXHandler::~CDXHandler(void)
{
};

bool CDXHandler::Init( const HWND _hWnd, const unsigned int _unWindowWidth, const unsigned int _unWindowHeight )
{
	m_pD3DObject = Direct3DCreate9( D3D_SDK_VERSION );
	if( m_pD3DObject == nullptr )
	{
		POST_MSGBOX( "Failed to create DX Object" );
		return false;
	}

	m_D3DPresentParam.BackBufferWidth				= _unWindowWidth;
	m_D3DPresentParam.BackBufferHeight				= _unWindowHeight;
	m_D3DPresentParam.BackBufferFormat				= D3DFMT_UNKNOWN;
	m_D3DPresentParam.BackBufferCount				= 1;
	m_D3DPresentParam.MultiSampleType				= D3DMULTISAMPLE_NONE;
	m_D3DPresentParam.MultiSampleQuality			= 0;
	m_D3DPresentParam.SwapEffect					= D3DSWAPEFFECT_DISCARD;
	m_D3DPresentParam.hDeviceWindow					= _hWnd;
	m_D3DPresentParam.Windowed						= true;
	m_D3DPresentParam.EnableAutoDepthStencil		= true;
	m_D3DPresentParam.AutoDepthStencilFormat		= D3DFMT_D24S8;
	m_D3DPresentParam.FullScreen_RefreshRateInHz	= D3DPRESENT_RATE_DEFAULT;
	m_D3DPresentParam.PresentationInterval			= D3DPRESENT_INTERVAL_DEFAULT;

	if( m_pD3DObject->CreateDevice(0, D3DDEVTYPE_HAL, m_D3DPresentParam.hDeviceWindow,
		D3DCREATE_HARDWARE_VERTEXPROCESSING, &m_D3DPresentParam, &m_pD3DDevice) )
	{
		POST_MSGBOX( "Failed to create device" );
		return false;
	}

	m_pScreenRender = new CDXScreenRender;
	m_pScreenRender->Init( &m_pD3DDevice, _unWindowWidth, _unWindowHeight );

	return true;
};

bool CDXHandler::Init( const char *_szFilePath )
{

	return true;
};

void CDXHandler::Release( void )
{
	if( m_pD3DObject != nullptr )
	{
		m_pD3DObject->Release();
		m_pD3DObject = nullptr;
	}

	if( m_pD3DDevice != nullptr )
	{
		m_pD3DDevice->Release();
		m_pD3DDevice = nullptr;
	}

	if( m_pScreenRender != nullptr )
	{
		m_pScreenRender->Release();
		delete m_pScreenRender;
		m_pScreenRender = nullptr;
	}
};

void CDXHandler::Clear( void )
{
	m_pD3DDevice->Clear( 0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 255, 255, 255 ), 1.0f, 0 );
};

void CDXHandler::Present( void )
{
	m_pD3DDevice->Present( 0, 0, 0, 0 );
};

void CDXHandler::BeginScene( void )
{
	m_pD3DDevice->BeginScene();
};

void CDXHandler::EndScene( void )
{
	m_pD3DDevice->EndScene();
};

void CDXHandler::Render( void )
{
	m_pScreenRender->Render();
};
